package cn.telling.sellercentre.service.impl;


import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import cn.telling.common.pager.PageVo;
import cn.telling.common.util.TellingConstance;
import cn.telling.common.util.UUIDUtil;
import cn.telling.product.service.IStoreProductService;
import cn.telling.product.service.ISupplyService;
import cn.telling.product.service.impl.StoreProductServiceImpl;
import cn.telling.product.vo.ShopProductVo;
import cn.telling.product.vo.StoreProductVo;
import cn.telling.product.vo.SupplyVo;
import cn.telling.product.vo.TelMarketPubHis;
import cn.telling.productapprove.service.IProductApproveService;
import cn.telling.productapprove.vo.ProductApproveVo;
import cn.telling.sellerCenter.service.ISellerBasePriceService;
import cn.telling.sellerCenter.service.ISellerConCentreService;
import cn.telling.sellerCenter.vo.ProductSortVo;
import cn.telling.sellerCenter.vo.QuotationVo;
import cn.telling.sellerCenter.vo.SellerBasePrice;
import cn.telling.sellerCenter.vo.ShopProductApproveVo;
import cn.telling.sellerCenter.vo.ShopProductAreaApproveVo;
import cn.telling.sellerCenter.vo.ShopProductAreaVo;
import cn.telling.sellercentre.dao.ISellerConCentreDao;


/**
 * @Description:卖家中心产品业务处理层实现
 * @author yanhaiwei
 */
@Service("sellerConCentreService")
public class SellerConCentreServiceImpl implements ISellerConCentreService {


	@Autowired	
	private ISellerConCentreDao sellerConCentreDao;
	
	@Autowired	
	private IProductApproveService productApproveService;
	
	@Autowired	
	private ISupplyService supplyService;
	@Autowired
	private ISellerBasePriceService sellerBasePriceService;
	@Autowired IStoreProductService storeProductService;
	/**获得卖家中心已上架、已下架、审核中产品列表 */
	@Override
	public List<ShopProductAreaVo> getSaleListByStatus(String userId,String saleType, String status, String conditions,String productfirstSort,String productSortId) {
		if(!"".equals(saleType) && saleType != null){
			saleType = getSaleType(Integer.parseInt(saleType));
		}
		
		return sellerConCentreDao.getSaleListByStatus(userId, saleType, status, conditions,productfirstSort, productSortId);
	}

	/**根据传入的销售类型(定向、非定向)返回销售模式*/
	private String getSaleType(int saleType){
		String result = "";
		switch(saleType){
			case 1 :
				result = TellingConstance.SALETYPE3 + "','" + TellingConstance.SALETYPE4;
				break;
			case 2 :
				result = TellingConstance.SALETYPE2;
				break;
			case 3 :
				result = TellingConstance.SALETYPE1;
				break;
			default:
				result = "";
				break;
		}
		return result;
	}
	/**根据产品列表 进行分类处理 */
	@Override
	public HashMap<String, List<ShopProductAreaVo>> getSaleListMap(List<ShopProductAreaVo> shopProductAreaVoList) {
		
		List<ShopProductAreaVo> newShopProductAreaVoList = new LinkedList<ShopProductAreaVo>();
		HashMap<String, List<ShopProductAreaVo>> shopProductAreaVoListMap = new LinkedHashMap<String, List<ShopProductAreaVo>>();
		
		if(shopProductAreaVoList != null && shopProductAreaVoList.size() > 0){
			for(int i = 0; i < shopProductAreaVoList.size(); i++){
				ShopProductAreaVo shopProductAreaVo = shopProductAreaVoList.get(i);
				if("1".equals(shopProductAreaVo.getIsShare())){//共享库存
					if(shopProductAreaVoListMap.get(shopProductAreaVo.getShareCode()) != null){//共享库存批编码
						shopProductAreaVoListMap.get(shopProductAreaVo.getShareCode()).add(shopProductAreaVo);
					}else {
						List<ShopProductAreaVo> list = new ArrayList<ShopProductAreaVo>();
						list.add(shopProductAreaVo);
						
						shopProductAreaVoListMap.put(shopProductAreaVo.getShareCode(), list);
					}
				}else {//0 非共享库存
					newShopProductAreaVoList.add(shopProductAreaVo);
				}
			}
		}
		
		if(newShopProductAreaVoList != null && newShopProductAreaVoList.size() > 0){
			shopProductAreaVoListMap.put("0", newShopProductAreaVoList);
		}
		return shopProductAreaVoListMap;
	}
	/**
	 * 判断是否存在基准价格
	 */
	@Override
	public boolean hasSellerBasePrice(String supplyId, String productId) {
		SellerBasePrice sellerBasePrice = sellerConCentreDao.getSellerBasePrice(supplyId, productId);
		if(sellerBasePrice != null){
			return true;
		}
		return false;
	}
	/**
	 * 获取基准价格
	 */
	@Override
	public SellerBasePrice getSellerBasePrice(String supplyId, String productId) {
		SellerBasePrice sellerBasePrice = sellerConCentreDao.getSellerBasePrice(supplyId, productId);
		if(sellerBasePrice != null){
			return sellerBasePrice;
		}
		return null;
	}
	/**已上架产品修改*/
	@Override
	public int onSaleModify(ShopProductAreaApproveVo shopProductAreaApproveVo) {
		
		if(shopProductAreaApproveVo != null){
			List<ShopProductAreaVo> shopProductAreaVoList = shopProductAreaApproveVo.getShopProductAreaVoList();
			if(shopProductAreaVoList != null && shopProductAreaVoList.size() > 0){
				for (int i = 0; i < shopProductAreaVoList.size(); i++) {
					ShopProductAreaVo shopProductAreaVo = shopProductAreaVoList.get(i);
					boolean hasChange = false;
					String remark = "";
					
					/**有价格修改*/
					BigDecimal priceRetailOnline = shopProductAreaVo.getPriceRetailOnline().setScale(2,BigDecimal.ROUND_HALF_EVEN);
					BigDecimal approvePrice = shopProductAreaVo.getApprovePrice().setScale(2, BigDecimal.ROUND_HALF_EVEN);
					if (!priceRetailOnline.equals(approvePrice)) {
						remark = "价格修改为:" + approvePrice.toString();
						hasChange = true;
					}
					
					/**有库存修改*/
					BigDecimal stockNumber = shopProductAreaVo.getStockNumber();
					BigDecimal approveStockNumber = new BigDecimal(shopProductAreaVo.getApproveStockNum());
					if (!stockNumber.equals(approveStockNumber)) {
						if (hasChange) {
							/**有价格修改*/
							remark += ",";
						}
						remark += "库存修改为:"+ approveStockNumber.toString();
						
						hasChange = true;
					}
					/**打补丁的做法  减去现有库存  因为在审核的时候是把原有库存加上的*/
					shopProductAreaVo.setApproveStockNum(Long.parseLong(String.valueOf(approveStockNumber.subtract(stockNumber))));
					
					String saleStatus = shopProductAreaVo.getSaleStatus();
					if("1".equals(saleStatus)){
						remark += "申请下架";
					}else if ("2".equals(saleStatus)) {
						remark += "申请上架";
					}
					
					if (hasChange) {
						shopProductAreaVo.setRemark(remark);
						continue;
					}
					
					shopProductAreaVoList.remove(shopProductAreaVo);
				}
			}
			
			/**没有进行修改*/
			if(shopProductAreaVoList.size() == 0){
				return 0;
			}
			shopProductAreaApproveVo.setShopProductAreaVoList(shopProductAreaVoList);
			
			/**根据列表里大小获得生成的审核Id*/
			String approveId[] = new String[shopProductAreaVoList.size()];
			for(int i = 0; i < shopProductAreaVoList.size(); i++){
				approveId[i] = productApproveService.findApproveId().toString();
				shopProductAreaApproveVo.setId(approveId);
			}			
			/**根据供货商产品信息提交产品审核申请*/
			sellerConCentreDao.insertShopProductApprove(shopProductAreaApproveVo);
			
			/**更新供应商产品区域销售状态*/
	     	// sellerConCentreDao.updateSupplyAreaSaleStatus(shopProductAreaApproveVo);
						 
			/**已上架产品 修改后自动审核  开始    除定向发布的集采产品不自动审核外其余都自动审核*/
			int productApproveNum = shopProductAreaVoList.size();
			
			/*
			if(shopProductAreaApproveVo.isBlean()){
				 /**1：竞价发表2:非定向发布，3：定向发布(到客户)，4：定向发布(到区域) 
				String saleType = StringHelperTools.nvl(shopProductAreaApproveVo.getSaleType());
				String product_del10 = StringHelperTools.nvl(shopProductAreaApproveVo.getProduct_del10());
				if(!((saleType.equals(TellingConstance.SALETYPE3) || saleType.equals(TellingConstance.SALETYPE4)) && "集采".equals(product_del10))){
					int count = 0;
					for (int i = 0; i < approveId.length; i++) {
						ProductApproveVo productApproveVo = new ProductApproveVo();
						productApproveVo.setId(shopProductAreaApproveVo.getId()[i]);
						productApproveVo.setApproveUser("1");// 默认为超级
						productApproveVo.setApproveStatus(TellingConstance.SALESTATUS3);//审核通过
						productApproveVo.setIsSysApprove("1");//系统自动审核
						count += productApproveService.Approve(productApproveVo);
					}
					
					productApproveNum = count;
				}
			}
			*/			
			/**已上架产品 修改后自动审核  结束*/			
			return productApproveNum;
		}
		return 0;
	}
	/**
	 * 修改通信市场产品发布历史 截止日期
	 */
	@Override
	public int updateTelMarketPubHis(String productId, String supplyAreaId) {
		return sellerConCentreDao.updateTelMarketPubHis(productId, supplyAreaId);
	}
	/**
	 * 入库基准价格
	 */
	@Override
	public int insertSellerBsePrice(SellerBasePrice sellerBasePrice) {
		return sellerConCentreDao.insertSellerBsePrice(sellerBasePrice);
	}
	/**
	 * 更新基准价格
	 */
	@Override
	public int updateSellerBasePrice(BigDecimal basePrice, BigDecimal userId,String supplyId, String productId) {
		return sellerConCentreDao.updateSellerBasePrice(basePrice, userId, supplyId, productId);
	}
	/**
	 * 记录单个通信市场产品发布历史
	 */
	@Override
	public int insertTelMarketPubHis(TelMarketPubHis telMarketPubHis) {
		return sellerConCentreDao.insertTelMarketPubHis(telMarketPubHis);
	}
	/**根据共享编码查询出共享产品列表  供共享使用*/
	@Override
	public Map<String, ShopProductAreaVo> getSupplyAreaByShareCode(String shareCode) {
		Map<String, ShopProductAreaVo> shopProductAreaVoMap = new HashMap<String, ShopProductAreaVo>();
		List<ShopProductAreaVo> shopProductAreaVoList = sellerConCentreDao.getSupplyAreaByShareCode(shareCode);
		
		if(shopProductAreaVoList != null && shopProductAreaVoList.size() > 0){
			for (ShopProductAreaVo shopProductAreaVo : shopProductAreaVoList) {
				String supplyAreaId = String.valueOf(shopProductAreaVo.getSupplyAreaId());
				shopProductAreaVoMap.put(supplyAreaId, shopProductAreaVo);
			}
			return shopProductAreaVoMap;
		}
		return null;
	}
	/**根据supplyAreaId 查询出供货商产品区域*/
	@Override
	public ShopProductAreaVo getSupplyAreaById(String supplyAreaId) {
		return sellerConCentreDao.getSupplyAreaById(supplyAreaId);
	}
	/**已上架产品 下架操作*/
	@Override
	public int onSaleOff(ShopProductAreaApproveVo shopProductAreaApproveVo) {
		if(shopProductAreaApproveVo != null){
			List<ShopProductAreaVo> shopProductAreaVoList = shopProductAreaApproveVo.getShopProductAreaVoList();
			if(shopProductAreaVoList != null && shopProductAreaVoList.size() > 0){
				for (int i = 0; i < shopProductAreaVoList.size(); i++) {
					ShopProductAreaVo shopProductAreaVo = shopProductAreaVoList.get(i);
					if ("1".equals(shopProductAreaVo.getSaleStatus())) {
						/**判断是否竞价状态*/
						if (TellingConstance.SALETYPE1.equals(shopProductAreaVo.getSaleType())) {
							sellerConCentreDao.UpdateContinuous(shopProductAreaVo);
							shopProductAreaVoList.remove(shopProductAreaVo);
						} else {
							shopProductAreaVo.setRemark("商品下架");
						}
					}else if("2".equals(shopProductAreaVo.getSaleStatus())) {
						shopProductAreaVo.setRemark("商品上架");
						BigDecimal stockNumber = shopProductAreaVo.getStockNumber();
						BigDecimal approveStockNumber = new BigDecimal(shopProductAreaVo.getApproveStockNum());
						shopProductAreaVo.setApproveStockNum(Long.parseLong(String.valueOf(approveStockNumber.subtract(stockNumber))));
					}else {
						shopProductAreaVoList.remove(shopProductAreaVo);
					}
				}
			}
			
			/**没有进行修改*/
			if(shopProductAreaVoList.size() == 0){
				return 0;
			}
			shopProductAreaApproveVo.setShopProductAreaVoList(shopProductAreaVoList);
			
			/**根据列表里大小获得生成的审核Id*/
			String approveId[] = new String[shopProductAreaVoList.size()];
			for(int i = 0; i < shopProductAreaVoList.size(); i++){
				approveId[i] = productApproveService.findApproveId().toString();
				shopProductAreaApproveVo.setId(approveId);
			}
			
			/**根据供货商产品信息提交产品审核申请*/
			sellerConCentreDao.insertShopProductApprove(shopProductAreaApproveVo);
			/**更新供应商产品区域销售状态*/
			sellerConCentreDao.updateSupplyAreaSaleStatus(shopProductAreaApproveVo);
			
			/**已上架产品 修改后自动审核  开始    除定向发布的集采产品不自动审核外其余都自动审核*/
			
			 int productApproveNum = shopProductAreaVoList.size();
			 /*
			if(shopProductAreaApproveVo.isBlean()){
				int count = 0;
				for (int i = 0; i < shopProductAreaVoList.size(); i++) {
					ShopProductAreaVo shopProductAreaVo = shopProductAreaVoList.get(i);
					/**1：竞价发表2:非定向发布，3：定向发布(到客户)，4：定向发布(到区域) 
					String saleType = StringHelperTools.nvl(shopProductAreaVo.getSaleType());
					String product_del10 = StringHelperTools.nvl(shopProductAreaVo.getProduct_del10());
					if(!((saleType.equals(TellingConstance.SALETYPE3) || saleType.equals(TellingConstance.SALETYPE4)) && "集采".equals(product_del10))){
						ProductApproveVo productApproveVo = new ProductApproveVo();
						productApproveVo.setId(shopProductAreaApproveVo.getId()[i]);
						productApproveVo.setApproveUser("1");// 默认为超级
						productApproveVo.setApproveStatus(TellingConstance.SALESTATUS3);//审核通过
						productApproveVo.setIsSysApprove("1");//系统自动审核
						count += productApproveService.Approve(productApproveVo);
						productApproveNum = count;
					}
				}
			 }
			 */
			/**已上架产品 修改后自动审核  结束*/			 
			return productApproveNum;
		}
		return 0;
	}

	/**批量更新基准价格*/
	@Override
	public int updateSellerBasePriceBatch(List<SellerBasePrice> sellerBasePriceList) {
		return sellerConCentreDao.updateSellerBasePriceBatch(sellerBasePriceList);
	}
	/**
	 * 记录通信市场产品发布历史
	 */
	@Override
	public int[] insertTelMarketPubHis(List<TelMarketPubHis> telMarketPubHisList) {
		return sellerConCentreDao.insertTelMarketPubHis(telMarketPubHisList);
	}
	/**批量更新通信市场产品发布历史 截止日期*/
	@Override
	public int updateTelMarketPubHisBatch(List<String> productIdList,List<String> supplyAreaIdList) {
		return sellerConCentreDao.updateTelMarketPubHisBatch(productIdList, supplyAreaIdList);
	}
	/**根据用户Id获得供应商类型    空   外部供应商  01   天音供应商     02 03厂家供应商*/
	@Override
	public String GetSupplyType(String userId) {
		return sellerConCentreDao.GetSupplyType(userId);
	}
	/**根据用户Id、销售类型(定向、非定向)、上下架状态、型号名称   获得供货商产品总数*/
	@Override
	public int GetShopProductCount(String userId, int saleType, String status,String modelName) {
		int count = 0;
		if (saleType == 0) {
			//获取所有销售类型产品总数
			count = sellerConCentreDao.GetShopProductCount(userId, null, status,modelName);
		} else {
			//获取指定销售类型产品总数
			count = sellerConCentreDao.GetShopProductCount(userId,GetSaleType(saleType), status,modelName);
		}
		return count;
	}
	/**根据传入的销售类型(定向、非定向)返回销售模式*/
	private String GetSaleType(int type) {
		String saleType = "";
		switch (type) {
		case 1:
			saleType = TellingConstance.SALETYPE3 + "','" + TellingConstance.SALETYPE4;
			break;
		case 2:
			saleType = TellingConstance.SALETYPE2;
			break;
		case 3:
			saleType = TellingConstance.SALETYPE1;
			break;
		default:
			break;
		}

		return saleType;
	}
	/**根据用户Id、销售类型(定向、非定向)、上下架状态、型号名称  分页获得供货商产品列表（分页）*/
	@Override
	public List<ShopProductVo> GetShopProductList(String userId, int saleType,String status, PageVo pageVo,String modelName) {
		List<ShopProductVo> shopProductVoList = null;
		if (saleType == 0) {
			//获取所有销售类型产品列表（分页）
			shopProductVoList = sellerConCentreDao.GetShopProductList(userId, null, status,pageVo,modelName);
		} else {
			//获取指定销售类型产品列表（分页）
			shopProductVoList = sellerConCentreDao.GetShopProductList(userId,GetSaleType(saleType), status, pageVo,modelName);
		}
		return shopProductVoList;
	}

	/**根据用户Id、销售类型(定向、非定向)、型号名称   获得审核中的供货商产品总数*/
	@Override
	public int GetApproveShopProductCount(String userId, int saleType,String modelName) {
		int count = 0;
		if (saleType == 0) {
			//获取审核中的所有销售类型产品总数
			count = sellerConCentreDao.GetApproveShopProductCount(userId, null,modelName);
		} else {
			//获取审核中的指定销售类型产品总数
			count = sellerConCentreDao.GetApproveShopProductCount(userId,GetSaleType(saleType),modelName);
		}
		
		return count;
	}
	/**根据用户Id、销售类型(定向、非定向)、型号名称  分页获得审核中的供货商产品列表（分页）*/
	@Override
	public List<ShopProductVo> GetApproveShopProductList(String userId, int saleType,PageVo pageVo,String modelName) {

		List<ShopProductVo> shopProductVoList = null;
		if (saleType == 0) {
			//获取审核中的所有销售类型产品列表（分页）
			shopProductVoList = sellerConCentreDao.GetApproveShopProductList(userId, null,pageVo,modelName);
		} else {
			//获取审核中的指定销售类型产品列表（分页）
			shopProductVoList = sellerConCentreDao.GetApproveShopProductList(userId,GetSaleType(saleType), pageVo,modelName);
		}
		
		return shopProductVoList;
	}
	/**根据供货商产品Id、销售状态(1 审核中、2 审核未通过、3  审核通过)、用户Id、上下架状态  获得该供货商产品的指定状态的发布信息 */
	@Override
	public ShopProductApproveVo GetApproveShopProductDetailList(long shopProductId, String saleStatus, String userId, String status) {
		
		// 获取供应商产品信息
		ShopProductVo shopProdctVo = sellerConCentreDao.GetShopProduct(shopProductId, userId);
		List<ShopProductAreaVo> shopProductAreaVoList = null;
		HashMap<String, List<ShopProductAreaVo>> map = new LinkedHashMap<String, List<ShopProductAreaVo>>();
		
		List<ShopProductAreaVo> newShopProductAreaVoList = new ArrayList<ShopProductAreaVo>();
		
		if (shopProdctVo != null) {
			// 获取供应商产品区域信息
			shopProductAreaVoList = sellerConCentreDao.GetShopProductAreaList(shopProductId, saleStatus, status);
		}
		
		if(shopProductAreaVoList != null && shopProductAreaVoList.size() > 0){
			for(int i = 0; i < shopProductAreaVoList.size(); i++){
				ShopProductAreaVo shopProductAreaVo = shopProductAreaVoList.get(i);
				if("1".equals(shopProductAreaVo.getIsShare())){
					if(map.get(shopProductAreaVo.getShareCode()) != null){
						map.get(shopProductAreaVo.getShareCode()).add(shopProductAreaVo);
					}else {
						List<ShopProductAreaVo> list = new ArrayList<ShopProductAreaVo>();
						list.add(shopProductAreaVo);
						
						map.put(shopProductAreaVo.getShareCode(), list);
					}
					
				}else {
					newShopProductAreaVoList.add(shopProductAreaVo);
				}
			}
		}
		
		map.put("0", newShopProductAreaVoList);

		ShopProductApproveVo shopProductApproveVo = new ShopProductApproveVo();
		shopProductApproveVo.setShopProductVo(shopProdctVo);
		shopProductApproveVo.setLstShopProductAreaVo(shopProductAreaVoList);
		shopProductApproveVo.setShopProductAreaVoMap(map);
		
		return shopProductApproveVo;
	}
	/**根据 供货商产品id 返回ShopProductVO*/
	@Override
	public ShopProductVo getOneShopProductVO(String id) {
		ShopProductVo vo  = sellerConCentreDao.getOneShopProductVO(id);
		return vo;
	}
	/**根据供应商产品信息提交产品审核申请*/
	@Override
	@Transactional(value = "txManager", isolation = Isolation.DEFAULT, propagation = Propagation.REQUIRED, rollbackFor = { Exception.class })
	public int ApproveShopProductChange(ShopProductApproveVo shopProductApproveVo) {
		// 获取需要更新List
		List<ShopProductAreaVo> shopProductAreaVoList = shopProductApproveVo.getLstShopProductAreaVo();
		
		// 没有上下架处理，才判断是否有价格或库存修改
		for (int i = shopProductAreaVoList.size() - 1; i >= 0; i--) {
			boolean hasChange = false;
			// 判断是否有修改
			ShopProductAreaVo shopProductAreaVo = shopProductAreaVoList.get(i);
			// 有下架操作
			if ("1".equals(shopProductAreaVo.getSaleStatus())) {
				if (TellingConstance.SALETYPE1.equals(shopProductAreaVo.getSaleType())) {
					// 如果是竞价产品,则判断当前竞价状态
					sellerConCentreDao.UpdateContinuous(shopProductAreaVo);
					shopProductAreaVoList.remove(shopProductAreaVo);
					
				} else {
					shopProductAreaVo.setRemark("商品下架");
				}
				continue;
			}
			
			String remark = "";
			
			// 有价格修改
			BigDecimal price = shopProductAreaVo.getPrice().setScale(2,BigDecimal.ROUND_HALF_EVEN);
			BigDecimal approvePrice = shopProductAreaVo.getApprovePrice().setScale(2, BigDecimal.ROUND_HALF_EVEN);
			if (!price.equals(approvePrice)) {
				remark = "修改价格为" + approvePrice.toString();
				hasChange = true;
			}
			
			// 有库存修改
			if (shopProductAreaVo.getApproveStockNum()!=0) {
				if (hasChange) {
					// 有价格修改
					remark += ",";
				}
				remark += "库存变更"+(shopProductAreaVo.getApproveStockNum() >= 0 ? "+" : "" ) + String.valueOf(shopProductAreaVo.getApproveStockNum());
				hasChange = true;
			}
			
			if (hasChange) {
				shopProductAreaVo.setRemark(remark);
				continue;
			}
			// 没有修改，删除该条
			shopProductAreaVoList.remove(shopProductAreaVo);
		}
		
		// 没有修改
		if (shopProductAreaVoList.size() == 0){
			return 0;
		}
		shopProductApproveVo.setLstShopProductAreaVo(shopProductAreaVoList);
		
		//取得生成的Id
		String approveId[]=new String[shopProductAreaVoList.size()];
		for(int i = 0; i < shopProductAreaVoList.size(); i++){
			approveId[i] = productApproveService.findApproveId().toString();
			shopProductApproveVo.setId(approveId);
		}
		
		// 生成修改申请
		sellerConCentreDao.ApproveShopProductChange2(shopProductApproveVo);

		// 更新状态
		sellerConCentreDao.UpdateShopProductStatus(shopProductApproveVo);
		 
		 int a=0;
		//发布产品 自动审核（王震追加2014-2-20） start
		if( shopProductApproveVo.isBlean()){

			//1：竞价发表2:非定向发布，3：定向发布(到客户)，4：定向发布(到区域)
			//定向发布的集采不自动审核
			if((shopProductApproveVo.getSaleType().equals(TellingConstance.SALETYPE3) || shopProductApproveVo.getSaleType().equals(TellingConstance.SALETYPE4))){
        	//以外的场合自动审核
			}else{
        	  
	      		for(int j=0;j<approveId.length;j++){
	    	        //对未勾选的产品审核
	    			ProductApproveVo submitPAVo = new ProductApproveVo();
	    			submitPAVo.setId(shopProductApproveVo.getId()[j]);
	    			submitPAVo.setApproveUser("1");// 默认为超级
	    			submitPAVo.setApproveStatus(TellingConstance.SALESTATUS3);
	    			submitPAVo.setIsSysApprove("1");//系统自动审核
	    			productApproveService.Approve(submitPAVo);
	    			
	    		}
	      		
	      		a = 1;
			}
		}
		//发布产品 自动审核（王震追加2014-2-20） end
		
		return a;
	}
	/**根据供应商产品信息提交上架申请 */
	@Override
	@Transactional(value = "txManager", isolation = Isolation.DEFAULT, propagation = Propagation.REQUIRED, rollbackFor = { Exception.class })
	public int ApproveShopProductReOnShelve(ShopProductApproveVo shopProductApproveVo) {
		
		// 获取需要更新List
		List<ShopProductAreaVo> shopProductAreaVoList = shopProductApproveVo.getLstShopProductAreaVo();
		for (int i = shopProductAreaVoList.size() - 1; i >= 0; i--) {
			boolean hasChange = false;
			// 判断是否有修改
			ShopProductAreaVo shopProductAreaVo = shopProductAreaVoList.get(i);
			// 有上架操作
			if ("1".equals(shopProductAreaVo.getSaleStatus())) {
				if (!TellingConstance.SALETYPE1.equals(shopProductAreaVo.getSaleType())) {
					shopProductAreaVo.setSaleStatus("2");
					shopProductAreaVo.setRemark("商品上架");
				}
				continue;
			}

			String remark = "";
			
			// 有价格修改
			BigDecimal price = shopProductAreaVo.getPrice().setScale(2,BigDecimal.ROUND_HALF_EVEN);
			BigDecimal approvePrice = shopProductAreaVo.getApprovePrice().setScale(2, BigDecimal.ROUND_HALF_EVEN);
			if (!price.equals(approvePrice)) {
				remark = "修改价格为" + approvePrice.toString();
				hasChange = true;
			}
			
			// 有库存修改
			if (shopProductAreaVo.getApproveStockNum()!=0) {
				if (hasChange) {
					// 有价格修改
					remark += ",";
				}
				remark += "库存变更"+(shopProductAreaVo.getApproveStockNum() >= 0 ? "+" : "" ) + String.valueOf(shopProductAreaVo.getApproveStockNum());
				hasChange = true;
			}
			
			if (hasChange) {
				shopProductAreaVo.setRemark(remark);
				continue;
			}
			
			// 没有修改，删除该条
			shopProductAreaVoList.remove(shopProductAreaVo);
		}
		
		// 没有修改
		if (shopProductAreaVoList.size() == 0) {
			return 0;
		}
		
		shopProductApproveVo.setLstShopProductAreaVo(shopProductAreaVoList);
		
		// 生成修改申请
		int i = 0;
		if (!TellingConstance.SALETYPE1.equals(shopProductAreaVoList.get(0).getSaleType())) {
			
			//取得生成的Id
			String approveId[]=new String[shopProductAreaVoList.size()];
			for(int j=0;j<shopProductAreaVoList.size();j++){
				approveId[j]=productApproveService.findApproveId().toString();
				shopProductApproveVo.setId(approveId);
			}
			
			i = sellerConCentreDao.ApproveShopProductChange2(shopProductApproveVo);
			i = sellerConCentreDao.UpdateShopProductStatus(shopProductApproveVo);
			
			//发布产品 自动审核（王震追加2014-2-20） start
			//1：竞价发表2:非定向发布，3：定向发布(到客户)，4：定向发布(到区域)
			//定向发布的集采不自动审核
			
			if( shopProductApproveVo.isBlean()){
	        if( (shopProductApproveVo.getSaleType().equals(TellingConstance.SALETYPE3) || shopProductApproveVo.getSaleType().equals(TellingConstance.SALETYPE4))){

	          }else{
				// 对勾选的产品审核
				for (int k = 0; k < approveId.length; k++) {
					ProductApproveVo submitPAVo = new ProductApproveVo();
					submitPAVo.setId(approveId[k]);
					submitPAVo.setApproveUser("1");// 默认为超级
					submitPAVo.setApproveStatus(TellingConstance.SALESTATUS3);
					submitPAVo.setIsSysApprove("1");//系统自动审核
					i = productApproveService.Approve(submitPAVo);
				}
			}
			}
	        
	      //发布产品 自动审核（王震追加2014-2-20） end
		} else {
			i = sellerConCentreDao.UpdateShopBidProductStatus(shopProductApproveVo);
		}
		
		// 更新状态
		return i;
	}
	
	@Override
	public Map<String, Object> QueryProductlist() {
				
		return sellerConCentreDao.QueryProductlist();
	}

	@Override
	public List<ProductSortVo> QueryProductSecondList(String sortId) {
		// TODO Auto-generated method stub
		return this.sellerConCentreDao.QueryProductSecondList(sortId);
	}
	
	@Override
	//xiu gai supply area0 里面的参数值
	public int updateSupplyArea0(ShopProductAreaApproveVo shopProductAreaApproveVo) {
		return sellerConCentreDao.updateSupplyArea0(shopProductAreaApproveVo);
	}

	@Override
	public String queryFor(long maijiaAreaId) {
		// TODO Auto-generated method stub
	    return	sellerConCentreDao.queryFor(maijiaAreaId);		
	}

	@Override
	public String offSaleByFronesupply(String supplyId) {
		
		String froneResult="";
		int countStatus=0;
		SupplyVo sp=this.supplyService.findSupplyBySupplyId(supplyId);
		List<ShopProductAreaVo> shopproductVo=this.getSaleListByStatus(sp.getUser_id().toString(), "", "1", "", "", "");
	    if(shopproductVo==null ){
	    	 froneResult="1";   //代表已经下架好了了所有的产品
	    	
	    }else{
	    	
		for(ShopProductAreaVo  shopvo: shopproductVo){
			if(shopvo.getPromotiondStatus()==null){				
				countStatus++;
			}
		}
	    if(countStatus==shopproductVo.size()){
			
		    int count= sellerConCentreDao.updateStatusByFronesupply(shopproductVo);
			if(count>0){
				froneResult="1";   //代表已经下架好了了所有的产品
			}
		}else{
			
			froneResult="0";      //如果含有活动的状态 那么就
		  }
	    
	   }		
	   return froneResult;
		
	}

	@Override
	public List<QuotationVo> searchForQuotation(String userId, String saleType,
			String status, String conditions, String productfirstSortId,
			String productSortid) {
		SupplyVo sv=supplyService.findSupplyByUserId(userId);
		return sellerConCentreDao.searchForQuotation(sv.getSupply_id().toString(), conditions, productfirstSortId, productSortid);
		
	}

	@Override
	@Transactional(value="txManager",isolation=Isolation.DEFAULT,propagation=Propagation.REQUIRED,rollbackFor={Exception.class})
	public void cancelReleaseProduct(String supplyAreaId,String supplyType) {
		ShopProductAreaVo vo=sellerConCentreDao.getSupplyAreaById(supplyAreaId);
		sellerConCentreDao.deleteSupplyArea(vo);
		if("1".equals(vo.getIsShare())){
			String shareCode=vo.getShareCode();
			Map<String, ShopProductAreaVo> shopProductAreaVoMap = null;
			shopProductAreaVoMap = this.getSupplyAreaByShareCode(shareCode);	
			if(shopProductAreaVoMap != null && shopProductAreaVoMap.size() > 0){
				for(Map.Entry<String, ShopProductAreaVo> entry : shopProductAreaVoMap.entrySet()) {
					ShopProductAreaVo shopProductAreaVo = entry.getValue();
					sellerConCentreDao.deleteSupplyArea(shopProductAreaVo);
				}
			}	
		}
		if((!"2".equals(vo.getSaleType()))&&TellingConstance.TELLING_SUPPLY_17.equals(supplyType)&&vo.getStockNumber().compareTo(BigDecimal.ZERO)==1){
			sellerConCentreDao.returnStock(vo);
		}
	}

	@Override
	public boolean checkRelease(String supplyAreaId, String userid) {
		return sellerConCentreDao.checkRelease(supplyAreaId, userid);
	}

	@Override
	public boolean onSaleUpdate(ShopProductAreaVo vo,BigDecimal newPrice,BigDecimal newStock) {
		if(newPrice!=null)
			vo.setApprovePrice(newPrice);
		else
			vo.setApprovePrice(vo.getPriceRetailOnline());
		if(newStock!=null)
			vo.setApproveStockNum(newStock.longValue());
		sellerConCentreDao.updateSupplyArea(vo);
		if("1".equals(vo.getIsShare())&&newStock!=null){//共享库存且有修改操作
			this.updateShareStock(vo,vo.getApproveStockNum());
		}
		return true;
	}
	
	public void updateShareStock(ShopProductAreaVo spVo,long newStock){
		String shareCode=spVo.getShareCode();
		Map<String, ShopProductAreaVo> shopProductAreaVoMap = null;
		if(!spVo.getStockNumber().equals(newStock)){
			shopProductAreaVoMap = this.getSupplyAreaByShareCode(shareCode);
		}	
		if(shopProductAreaVoMap != null && shopProductAreaVoMap.size() > 0){
			for(Map.Entry<String, ShopProductAreaVo> entry : shopProductAreaVoMap.entrySet()) {
				ShopProductAreaVo shopProductAreaVo = entry.getValue();
				shopProductAreaVo.setShopProductId(shopProductAreaVo.getShopProductId());
				shopProductAreaVo.setApprovePrice(shopProductAreaVo.getPriceRetailOnline());
				shopProductAreaVo.setSaleType(spVo.getSaleType());
				shopProductAreaVo.setApproveStockNum(new BigDecimal(newStock).longValue());
				sellerConCentreDao.updateSupplyArea(shopProductAreaVo);
			}
		}	
	}
	@Override
	public boolean verifyBasePrice(ShopProductAreaVo vo,BigDecimal newPrice) {
	    /** 所有供应商，如果发布的产品有基准价格，则要验证基准价格 */
        boolean hasBasePrice = sellerBasePriceService.hasSellerBasePrice(vo.getSupplyId().toString(), vo.getProductId().toString());		        
        if (hasBasePrice) {		        	
                /** 存在基准价格进行比对 ±30%可发布*/
                SellerBasePrice sellerBasePrice = sellerBasePriceService.getSellerBasePrice(vo.getSupplyId().toString(),vo.getProductId().toString());
                BigDecimal basePrice = sellerBasePrice.getBasePrice().setScale(2, BigDecimal.ROUND_HALF_EVEN);
                BigDecimal floatBase = new BigDecimal(0.30).setScale(2, BigDecimal.ROUND_HALF_EVEN);
                BigDecimal floatPrice = basePrice.multiply(floatBase);
                newPrice = newPrice.setScale(2, BigDecimal.ROUND_HALF_EVEN);
                if ( newPrice.compareTo(basePrice.add(floatPrice)) > 0|| newPrice.compareTo(basePrice.subtract(floatPrice)) < 0) {
                	return false;	
                }else{
                	return true;
                }
        }
        return true;
	}
}












